package com.huilian.iotbox.admin.wap.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.wap.dao.MoneyWithdrawDao;
import com.huilian.iotbox.admin.wap.service.MoneyWithdrawInvoiceInfoService;
import com.huilian.iotbox.admin.wap.service.MoneyWithdrawService;
import com.huilian.iotbox.admin.wap.service.UserBankCardService;
import com.huilian.iotbox.admin.wap.service.UserService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.MoneyWithdrawDto;
import com.huilian.iotbox.data.dto.UserDto;
import com.huilian.iotbox.data.enums.InvoiceFlagEnum;
import com.huilian.iotbox.data.enums.MoneyTypeEnum;
import com.huilian.iotbox.data.enums.MoneyWithdrawStatusEnum;
import com.huilian.iotbox.data.po.MoneyWithdraw;
import com.huilian.iotbox.data.po.MoneyWithdrawInvoiceInfo;
import com.huilian.iotbox.data.po.User;
import com.huilian.iotbox.data.po.UserBankCard;
import com.huilian.iotbox.data.service.UserBalanceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author 谢洛涛
 * @date 2021/4/8 9:23
 */
@Service
@Slf4j
public class MoneyWithdrawServiceImpl implements MoneyWithdrawService {
    @Resource
    private MoneyWithdrawDao moneyWithdrawDao;
    @Autowired
    private UserService userService;

    @Autowired
    private UserBankCardService userBankCardService;
    @Autowired
    private MoneyWithdrawInvoiceInfoService moneyWithdrawInvoiceInfoService;
    @Autowired
    private UserBalanceService userBalanceService;

    @Override
    public PageInfo findMoneyWithdrawList(MoneyWithdraw moneyWithdraw) {
        PageHelper.startPage(moneyWithdraw.getPageNum(), moneyWithdraw.getPageSize());
        PageInfo pageInfo = new PageInfo(moneyWithdrawDao.findMoneyWithdrawList(moneyWithdraw));
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse AddMoneyWithdraw(MoneyWithdrawDto moneyWithdrawDto) throws Exception {
        moneyWithdrawDto.setUserId(moneyWithdrawDto.getUserInfo().getId());
        // 查询用户余额
        User user = userService.findUserById(moneyWithdrawDto.getUserInfo().getId());
        if (user != null) {
            moneyWithdrawDto.setMobile(user.getMobile());
            BigDecimal balance = null;
            // 获取提现类型的余额
            if (MoneyTypeEnum.BALANCE.getCode().equals(moneyWithdrawDto.getWithdrawType())) {
                balance = user.getBalance();
            }
            if (moneyWithdrawDto.getMoney().compareTo(balance) > 0) {
                throw new Exception("余额不足");
            }
            BigDecimal waitInvoiceMoney = new BigDecimal("0");
            //平台扣除税点
            BigDecimal platformTax = BigDecimal.ZERO;
            //提现金额
            BigDecimal totalMoney = moneyWithdrawDto.getMoney();
            moneyWithdrawDto.setPoundage(BigDecimal.ZERO);  //手续费
            //查询用户未开发票记录,获取未开票金额
            totalMoney = totalMoney.add(waitInvoiceMoney);
            /**
             * 平台代替开发票
             */
            if ((InvoiceFlagEnum.REPLACEINVOICE.getCode()).equals(moneyWithdrawDto.getInvoiceFlag())) {
                // 判断是提现平台收款余额 或分润余额 （平台收款余额提现不需要手续费）
//                if (MoneyTypeEnum.COMMISSION_BALANCE.getCode().equals(moneyWithdrawDto.getWithdrawType())) {
                    // 根据UserId查询是否是机构和机构的手续费
//                    AgencyDto agencyDto = agencyService.getUserAgencyByUserId(moneyWithdrawDto.getUserInfo().getId());
//                    if (agencyDto != null && agencyDto.getWithdrawRate() != null) {
//                        platformTax = agencyDto.getWithdrawRate();
//                    } else {
                        platformTax = new BigDecimal("0.06");
//                    }
//                }
                moneyWithdrawDto.setSignInStatus(1);
            } else {
                // 判断是提现平台收款余额 或分润余额 （平台收款余额提现不需要手续费）
//                if (MoneyTypeEnum.COMMISSION_BALANCE.getCode().equals(moneyWithdrawDto.getWithdrawType())) {
                    if (!("02".equals(moneyWithdrawDto.getInvoiceTaxType()))) {
                        platformTax = new BigDecimal("0.03");
                    }
//                }
                moneyWithdrawDto.setSignInStatus(0);
            }
            moneyWithdrawDto.setTax(totalMoney.multiply(platformTax));
            moneyWithdrawDto.setPlatformTax(platformTax);
            //计算实际到账金额
            moneyWithdrawDto.setActualAccount(moneyWithdrawDto.getMoney().subtract(moneyWithdrawDto.getPoundage()).subtract(moneyWithdrawDto.getTax()));
            moneyWithdrawDto.setInvoiceMoney(moneyWithdrawDto.getMoney().add(waitInvoiceMoney).subtract(moneyWithdrawDto.getPoundage()).subtract(moneyWithdrawDto.getTax()));
            moneyWithdrawDto.setStatus(MoneyWithdrawStatusEnum.WAITDEALWITH.getCode());
            //添加提现记录
            moneyWithdrawDao.addMoneyWithdraws(moneyWithdrawDto);

            UserBankCard userBankCard = userBankCardService.getBindUserBankCardByType(moneyWithdrawDto.getUserId(), moneyWithdrawDto.getType());
            if (userBankCard.getCount() != null) {
                userBankCard.setCount(userBankCard.getCount() + 1);
            } else {
                userBankCard.setCount(1);
            }
            // 添加提现次数
            userBankCardService.updateUserBankCardCount(userBankCard);


            // 扣除余额

            UserDto userDto = new UserDto();
            userDto.setId(user.getId());
            userDto.setSubtractMoney(moneyWithdrawDto.getMoney());
            userDto.setMoneyType(moneyWithdrawDto.getWithdrawType());
            userBalanceService.subtractBalance(userDto, 0);

            if (InvoiceFlagEnum.OWNINVOICE.getCode().equals(moneyWithdrawDto.getInvoiceFlag())) {
                for (int i = 0; i < moneyWithdrawDto.getInvoicePhotoList().size(); i++) {
                    MoneyWithdrawInvoiceInfo invoiceInfo = new MoneyWithdrawInvoiceInfo();
                    invoiceInfo.setInvoicePhoto(moneyWithdrawDto.getInvoicePhotoList().get(i));
                    invoiceInfo.setInvoiceDate(moneyWithdrawDto.getInvoiceDate());
                    invoiceInfo.setWithdrawId(moneyWithdrawDto.getId());
                    moneyWithdrawInvoiceInfoService.insert(invoiceInfo);
                }
            }
            return ServerResponse.createBySuccess("申请成功");
        } else {
            throw new Exception("提现用户信息异常，请重试或联系管理员");
        }

    }
}
